package com.gwsdk.open;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import com.gwsdk.paysdk.Geetest.GeetestManager;
import com.gwsdk.paysdk.acitvityV2.GWLoginActivity;
import com.gwsdk.paysdk.bean.LoginModel;
import com.gwsdk.paysdk.bean.SdkDomain;
import com.gwsdk.paysdk.bean.privacy.PrivacyManager;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.floatview.GWFloatView;
import com.gwsdk.paysdk.http.process.DeviceOnlineProcess;
import com.gwsdk.paysdk.manager.GWGameManager;
import com.gwsdk.paysdk.manager.GWMqttManager;
import com.gwsdk.paysdk.utils.AppStatus;
import com.gwsdk.paysdk.utils.AppStatusManager;
import com.gwsdk.paysdk.utils.AppUtils;
import com.gwsdk.paysdk.bean.InitModel;
import com.gwsdk.paysdk.bean.GWPayModel;
import com.gwsdk.paysdk.bean.PersonalCenterModel;
import com.gwsdk.paysdk.bean.AntiAddictionModel;
import com.gwsdk.paysdk.bean.UploadRole;
import com.gwsdk.paysdk.dialog.DialogUtil;
import com.gwsdk.paysdk.dialog.HideBallDialog;
import com.gwsdk.paysdk.utils.GWLog;
import com.gwsdk.paysdk.utils.ScreenshotUtils;
import com.gwsdk.paysdk.utils.SharedPreferencesUtils;
import com.gwsdk.paysdk.utils.ToastUtil;

public class GWApi {

    private static final String TAG = "GWApiFactory";

    private static Activity mContext;
    private static Context mCon;

    public boolean isLogining = false;
    /**
     * 退出回调接口
     */
    private IGPExitObsv exitObsv;

    /**
     * 个人中心退出回调接口，判断用不能合并
     */
    protected IGPUserObsv mUserObsv;


    /**
     * 防沉迷到时间通知
     */
    private AnnounceTimeCallBack announceTimeCallBack;
    private LogoutCallback logoutCallback;
    private RealNameAuthenticationCallback authenticationCallback;

    private boolean floatingIsShow = false;
    private boolean LoginfloatingIsShow = false;

    private static GWApi instance;

    public static GWApi getApi() {
        if (null == instance) {
            instance = new GWApi();
        }
        return instance;
    }

    private GWApi() { }

    public Activity getContext() {
        return mContext;
    }

    /**
     * @param application Application
     */
    public void initApplication(Application application) {

    }

    /**
     * 初始化方法
     *
     */
    public void init(Context con) {
        init(con, true, null);
    }

    public void init(Context con, IGPSDKInitObsv initObsv) {
        init(con, true, initObsv);
    }

    public void init(final Context con, boolean isDebug) {
        init(con, isDebug, null);
    }



    public void init(final Context con, boolean isDebug, IGPSDKInitObsv initObsv) {
        GWLog.s("sdk", "-- init --");
        if (null == con) {
            GWLog.e(TAG, "初始化失败，上下文为空!");
            return;
        }
        GWLog.isDebug = isDebug;
        mContext = (Activity) con;
        mCon = con;
        GWMqttManager.getInstance().init(con);
        GWGameManager.getInstance().initIM(con);
        InitModel.init().doInit(con, initObsv);
//        UpDateUtils.getInstance().CheckForUpdates(mCon);
        AppStatusManager.getInstance().setAppStatus(AppStatus.STATUS_NORMAL);
    }





    public void startlogin(Activity context){
        if (null == context) {
            GWLog.e(TAG, "fun#login context is null");
            return;
        }
        mContext = context;
        if (!SdkDomain.getInstance().haveReadGameInfo()) {
            GWLog.e(TAG, "startlogin# sdk未初始化！");
            ToastUtil.show(context, "请先初始化sdk后再调用登录");
            return;
        }
        if(LoginModel.instance().isLogin()){
            GWLog.e(TAG, "startlogin# 请注销登录后再调用登录方法");
            return;
        }

        Constant.showedNoteDialog = false;
        boolean autoLogin = SharedPreferencesUtils.getInstance().getAutoLogin(context);
        if(autoLogin && !SharedPreferencesUtils.getInstance().getIsLogout(context) &&
                !SharedPreferencesUtils.getInstance().getIsThreeLogin(context) &&
                !GeetestManager.getInstance().isVerify()){
            //如果开启了自动登录、上次没有注销登录、上次不是QQ微信第三方快捷登录、没有开启极验，则调用自动登录
            autologin(context);
        }else{
            //调用登录接口
            login(context);
        }
    }

    public void setLoginCallback(IGPUserObsv mUserObsv) {
        this.mUserObsv = mUserObsv;
    }

    /**
     * sdk 登录
     */
    private void login(Activity context) {
        GWLog.e(TAG, "startlogin-login");
        if (null == context) {
            GWLog.e(TAG, "fun#startlogin context is null");
            return;
        }
        mContext = context;
        Intent loginIntent = new Intent(context, GWLoginActivity.class);
        loginIntent.putExtra("isAutoLogin",false);
        mContext.startActivity(loginIntent);
    }

    /**
     * sdk 自动登录
     *
     */
    private void autologin(final Activity context) {
        if (null == context) {
            GWLog.e(TAG, "fun#startlogin context is null");
            return;
        }
        mContext = context;
        String account = SharedPreferencesUtils.getInstance().getLoginAccount(context);
        String uid = SharedPreferencesUtils.getInstance().getLoginUid(context);
        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(uid)){
            GWLog.w("自动登录","账号："+account);
            Intent intent = new Intent(context, GWLoginActivity.class);
            intent.putExtra("isAutoLogin",true);
            intent.putExtra("phone",account);
            intent.putExtra("user_id",uid);
            mContext.startActivity(intent);
        }else {
            login(context);
        }
    }

    /**
     * 验证登录
     */
    public boolean isLogin() {
        return LoginModel.instance().isLogin();
    }

    /**
     * 注销
     */
    public void loginout(Activity context) {
        isLogining = false; //登录结束
        PersonalCenterModel.getInstance().clearUserLoginInfo(context, logoutCallback);

    }

    /**
     * 弹窗注销
     */
    public void PopuExt(Activity context) {

        isLogining = false;//切换账号
        PersonalCenterModel.getInstance().clearUserLoginInfoShowDialog(context, logoutCallback);
    }

    /**
     * 退出
     */
    public void exitDialog(Context context, IGPExitObsv exitObsv) {



        if (null == context) {
            GWLog.e(TAG, "fun#startlogin context is null");
            return;
        }
        if (null != exitObsv) {
            this.exitObsv = exitObsv;
        } else {
            this.exitObsv = null;
            GWLog.w(TAG, "fun#startlogin IGPExitObsv is null");
        }

        DialogUtil.gw_alert_exit((Activity) context);
    }

    /**
     * 开始支付
     *
     * @param orderInfo 商品信息
     * @param pck       支付回调
     */
    public void pay(Context context, OrderInfo orderInfo, PayCallback pck) {
        GWLog.e(TAG, orderInfo.toString());
        GWPayModel.Instance().pay(context, orderInfo, pck);
    }
    /**
     * 角色信息上传
     * @param roleCallBack 回调
     */
    public void uploadRole(RoleInfo roleinfo, UploadRoleCallBack roleCallBack) {
        UploadRole uploadRole = new UploadRole(roleinfo, roleCallBack);
        uploadRole.upload();
    }

    public void allowPrivacy(Activity activity, PrivacyCallback privacyCallback) {
        if (activity == null){
            GWLog.e(TAG,"activity is null");
            return;
        }
        PrivacyManager.getInstance().allowPrivacy(activity, privacyCallback);
    }


    @SuppressLint("NewApi")
    public void startFloating(final Context context) {
        if (!floatingIsShow && HideBallDialog.IsShow) {
            floatingIsShow = true;
            GWLog.i(TAG, "fun#startFloating");
            mContext.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    GWFloatView.getInstance(mContext).show();
                }
            });
        }
    }

    public void stopFloating(Context context) {
        if (floatingIsShow) {
            floatingIsShow = false;
            GWLog.i(TAG, "fun#stopFloating");
            mContext.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    GWFloatView.getInstance(mContext).close();
                }
            });
        }
    }

    /**
     * 游戏从后台开始，开始计时
     */
    public void onResume(Activity context) {
        AntiAddictionModel.getInstance().requestAntiAddictionInfo(context); //用户上线，查询防沉迷信息
        AppStatusManager.getInstance().startTime();
        AppStatusManager.appStatusManager.getRoomInfo();
        //请求设备上线
        DeviceOnlineProcess deviceOnlineProcess = new DeviceOnlineProcess(context);
        deviceOnlineProcess.post();
        if (FlagControl.isLogin && FlagControl.isFloatingOpen&&!LoginfloatingIsShow) {
            GWLog.w(TAG,"开启悬浮球");
            startFloating(context);
        }
    }

    public void onPause(Activity context) {
        GWApi.getApi().stopFloating(context);  //关闭悬浮球
    }

    /**
     * 游戏进入后台或退出游戏时，请求下线
     */
    public void onStop(final Activity activity) {
        if (!AppUtils.isAppOnForeground(activity)){
            GWLog.w(TAG,"游戏界面进入后台运行");
            InitModel.init().offLine(activity, false);
            AppStatusManager.getInstance().stopTime();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        ScreenshotUtils.getInstance().ActivityResult(requestCode,resultCode,data);
    }

    public void onDestroy() {
        ScreenshotUtils.getInstance().onDestroy();
        if(DialogUtil.lDialog!=null&&DialogUtil.lDialog.isShowing()){
            DialogUtil.lDialog.dismiss();
        }
    }

    public IGPUserObsv getLoginCallback() {
        isLogining = false; //登录结束
        return mUserObsv;
    }

    protected IGPExitObsv getExitObsv() {
        return exitObsv;
    }

    //设置注销回调
    public void initLogoutCallback(LogoutCallback logoutCallback) {
        this.logoutCallback = logoutCallback;
    }

    public LogoutCallback getLogoutClaaback(){
        if (logoutCallback!=null){
            return logoutCallback;
        }
        return null;
    }

    //实名认证回调
    public void initRealNameAuthenticationCallback(RealNameAuthenticationCallback authenticationCallback) {
        this.authenticationCallback = authenticationCallback;
    }

    /**
     * 实名认证
     */
    public RealNameAuthenticationCallback getRealNameAuthenticationCallback(){
        if (authenticationCallback == null){
            return null;
        }

        return authenticationCallback;
    }

    /**
     * 防沉迷时间提醒
     */
    public AnnounceTimeCallBack getAnnounceTimeCallBack() {
        if (announceTimeCallBack == null) {
            return null;
        }
        return announceTimeCallBack;
    }

}
